// by leili
UI.SimpleMenu = Class.create({
	initialize : function(parent,options,data) {
		this.parent = $(parent);
		Object.extend(this,options);
		this.data = data;
		this.root = this.renderRoot();
		this.process = this.process.bindAsEventListener(this);
		this.release = this.release.bindAsEventListener(this);
		
		this.root.titleTd.observe("click",this.process);
	},
	release : function(event){
		if(!event.upFind(this.root)){
			this.close();
			$(document.body).stopObserving("mousedown",this.release);
		}
			
	},
	close : function(){
		this.child.remove();
		this.child = null;
	},
	open : function(){
		this.child = this.renderChilds();
		this.root.insert(this.child);
		$(document.body).observe("mousedown",this.release);
	},
	process : function(event){
		if(this.child)
			this.close();
		else
			this.open();
	},
	renderRoot : function(){
		var root = new Element("div");
		root.addClassName("simpleMenu_root");
		root.setStyle({cursor:"pointer"});
		this.parent.insert(root);
		
		var table = new Element("table");
		root.insert(table);
		
		var tbody = new Element("tbody");
		table.insert(tbody);
		
		var tr = new Element("tr");
		tbody.insert(tr);
		
		var imgTd = new Element("td");
		tr.insert(imgTd);
		
		if(this.imgUrl){
			var img = new Element("img");
			img.src = this.imgUrl;
			imgTd.insert(img);
		}

		
		var textTd = new Element("td");
		tr.insert(textTd);
		
		textTd.insert(this.title);
		root.titleTd = textTd;
		return root;
	},
	renderChilds :function(){
		var div = new Element("div");
		div.addClassName("simpleMenu");
		div.setStyle({position:"absolute",zIndex:10030});
		
		var table = new Element("table");
		div.insert(table);
		var tbody = new Element("tbody");
		table.insert(tbody);
		
		this.data.each((function(value){
			var tr = new Element("tr");
			tbody.insert(tr);
			var imgTd = new Element("td");
			tr.insert(imgTd);
			
			if(value.imgUrl){
				var img = new Element("img");
				img.src = value.imgUrl;
				imgTd.insert(img);
			}
			
			var textTd = new Element("td");
			tr.insert(textTd);
			
			var a = new Element("a",{href:value.url||'javascript:Prototype.emptyFunction()'});
			
			var temp = (function(){
				(value.callback||Prototype.emptyFunction).call(this);
				this.close();
				a.stopObserving("mouseup",temp);
				$(document.body).stopObserving("mousedown",this.release);
			}).bindAsEventListener(this);
			
			a.observe("mouseup",temp);
			
			a.addClassName("simpleMenu_element");
			a.setStyle({left:(0+this.parent.cumulativeOffset()[0])+"px",top:this.parent.cumulativeOffset()[1]+this.root.getHeight()+"px"});
			textTd.insert(a);
			a.insert(value.title);
		}).bind(this));
		
		return div;
	}
});